<?php
namespace app\libs;
use yii;
use yii\data\Pagination;
define("CURL_TIMEOUT",   2000);
define("URL",           "https://openapi.youdao.com/v2/correct_writing_text");
define("IMAGEURL",       "https://openapi.youdao.com/correct_writing_image");
define("APP_KEY",        "41eccc99ab52d688"); // 替换为您的应用ID
define("SEC_KEY",        "GbIdsPRchwaDdZDGUX5VifbAVuYBYnI6"); // 替换为您的密钥

class Write
{
    /**
     * type 1文字批改，2图片批改
     * grade 批改等级 不考虑级别，单纯评价句子好坏	default 小学elementary     初中junior    高中high     四级cet4        六级cet6   考研graduate   托福toefl   GREgre   雅思ielts
     * 作文批改
     */
    public static function writeCorrect($q,$type,$grade){
        $url = $type==1?URL:IMAGEURL;
        if($type == 1){
            $q = self::strToUtf8($q);
            $q = self::ToSBC($q);
        }
        $result = self::do_request($q,$grade,$url,$type);
        return $result;
    }

    public static function do_request($q,$grade,$url,$type)
    {

//        $modelContent = self::ToSBC($modelContent);
        $salt = self::create_guid();
        $args = array(
            'q' => $q,
            'appKey' => APP_KEY,
            'salt' => $salt,
        );
        $curtime = strtotime("now");
        $args['curtime'] = $curtime;
//        $grade = "ielts";
        $args['grade'] = $grade;
//        $args['modelContent'] = $modelContent;
//        $args['title'] = $title;
        $args['signType'] = "v3";
        $signStr = APP_KEY . self::truncate($q,$type) . $salt . $curtime . SEC_KEY;
        $args['sign'] = hash("sha256", $signStr);
        $ret = self::call($url, $args);
        return $ret;
    }

// 发起网络请求
    public static function call($url, $args=null, $method="post", $testflag = 0, $timeout = CURL_TIMEOUT, $headers=array())
    {
        $ret = false;
        $i = 0;
        while($ret === false)
        {
            if($i > 1)
                break;
            if($i > 0)
            {
                sleep(1);
            }
            $ret = self::callOnce($url, $args, $method, false, $timeout, $headers);
            $i++;
        }
        return $ret;
    }

    public static function callOnce($url, $args=null, $method="post", $withCookie = false, $timeout = CURL_TIMEOUT, $headers=array())
    {
        $ch = curl_init();
        if($method == "post")
        {
            $data = self::convert($args);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
            curl_setopt($ch, CURLOPT_POST, 1);
        }
        else
        {
            $data = convert($args);
            if($data)
            {
                if(stripos($url, "?") > 0)
                {
                    $url .= "&$data";
                }
                else
                {
                    $url .= "?$data";
                }
            }
        }
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        if(!empty($headers))
        {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        }
        if($withCookie)
        {
            curl_setopt($ch, CURLOPT_COOKIEJAR, $_COOKIE);
        }
        $r = curl_exec($ch);
        curl_close($ch);
        return $r;
    }

    public static function convert(&$args)
    {
        $data = '';
        if (is_array($args))
        {
            foreach ($args as $key=>$val)
            {
                if (is_array($val))
                {
                    foreach ($val as $k=>$v)
                    {
                        $data .= $key.'['.$k.']='.rawurlencode($v).'&';
                    }
                }
                else
                {
                    $data .="$key=".rawurlencode($val)."&";
                }
            }
            return trim($data, "&");
        }
        return $args;
    }

// uuid generator
    public static function create_guid(){
        $microTime = microtime();
        list($a_dec, $a_sec) = explode(" ", $microTime);
        $dec_hex = dechex($a_dec* 1000000);
        $sec_hex = dechex($a_sec);
        self::ensure_length($dec_hex, 5);
        self::ensure_length($sec_hex, 6);
        $guid = "";
        $guid .= $dec_hex;
        $guid .= self::create_guid_section(3);
        $guid .= '-';
        $guid .= self::create_guid_section(4);
        $guid .= '-';
        $guid .= self::create_guid_section(4);
        $guid .= '-';
        $guid .= self::create_guid_section(4);
        $guid .= '-';
        $guid .= $sec_hex;
        $guid .= self::create_guid_section(6);
        return $guid;
    }

    public static function create_guid_section($characters){
        $return = "";
        for($i = 0; $i < $characters; $i++)
        {
            $return .= dechex(mt_rand(0,15));
        }
        return $return;
    }

    public static function truncate($q,$type) {
        $len = $type==1?self::utf8_strlen($q):strlen($q);
        if($type == 1){
            return $len <= 20 ? $q : (mb_substr($q, 0, 10) . $len . mb_substr($q, $len - 10, $len));
        }else{
            return $len <= 20 ? $q : (substr($q, 0, 10) . $len . substr($q, $len - 10, $len));
        }
    }

    public static function utf8_strlen($string = null) {
// 将字符串分解为单元
        preg_match_all("/./us", $string, $match);
// 返回单元个数
        return count($match[0]);
    }

    public static function ensure_length(&$string, $length){
        $strlen = strlen($string);
        if($strlen < $length)
        {
            $string = str_pad($string, $length, "0");
        }
        else if($strlen > $length)
        {
            $string = substr($string, 0, $length);
        }
    }

    public static function strToUtf8($str){
        $encode = mb_detect_encoding($str, array("ASCII",'UTF-8',"GB2312","GBK",'BIG5'));
        if($encode == 'UTF-8'){
            return $str;
        }else{
            return mb_convert_encoding($str, 'UTF-8', $encode);
        }
    }
    public static function ToSBC($q)
    {
        $q=str_replace('，',',',$q);
        $q=str_replace('（','(',$q);
        $q=str_replace('）',')',$q);
        $q=str_replace('。','.',$q);
        $q=str_replace('‘',"'",$q);
        $q=str_replace('’',"'",$q);
        $q=str_replace('？',"?",$q);
        $q=str_replace('：',":",$q);
        $q=str_replace('；',";",$q);
        return $q;
    }
}
